<template>
  <a-card v-if="FriendStore">
    <template #title>
      <span>{{ FriendStore.friendnick }} 的配置</span>
    </template>
    <!-- 示例配置项 -->
    <a-form auto-label-width>
      <a-form-item field="isconfirmpay" label="自动收款">
        <a-switch v-model="FriendStore.isconfirmpay" @change="(value) => handleConfirmpayChange(Boolean(value))"/>
      </a-form-item>
      <a-form-item field="isopenai" label="AI回复">
        <a-switch v-model="FriendStore.isopenai" @change="(value) => handleOpenaiChange(Boolean(value))"/>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script lang="ts" setup>
  import { watch,ref,reactive } from 'vue';  
  import { useFriendStore } from '@/store';
  import { Message } from '@arco-design/web-vue'
   import { editFriend } from '@/api/weixin';

  const FriendStore = useFriendStore();

  const props = defineProps<{
    selectedWxid: string;
  }>();
  
  const forward = reactive({
    ownerWxid: props.selectedWxid,
    wxid: '',
    nick: '',
    fromwxid: '',    
    fromnick: '',
  }); // 用于存储转发的目标微信号
  // 处理保存群消息开关
  const handleConfirmpayChange = async (confirmpay: boolean) => {
    try {
      const res: any = await editFriend({
        mywxid: props.selectedWxid  ,
        wxid: FriendStore.friendwxid,
        field: {
          isconfirmpay: confirmpay ? 1 : 0,
        },
      });
      if (res.code === 20000) {
        Message.success('设置成功');
        FriendStore.selectedFriend(
          res.data.wxid,
          res.data.avatarMaxUrl,
          res.data.nick,
          res.data.remark,
          Boolean(res.data.isopenai),
          Boolean(confirmpay), 
          )
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };
  const handleOpenaiChange = async (openai: boolean) => {
    try {
      const res: any = await editFriend({
        mywxid: props.selectedWxid  ,
        wxid: FriendStore.friendwxid,
        field: {
          isopenai: openai ? 1 : 0,
        },
      });
      if (res.code === 20000) {
        Message.success('设置成功');
        FriendStore.selectedFriend(
          res.data.wxid,
          res.data.avatarMaxUrl,
          res.data.nick,
          res.data.remark,
          Boolean(openai), 
          Boolean(res.data.isconfirmpay),          
        )
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };
  // 监听群变化
  watch(
    () => FriendStore.friendwxid,
    (newWxid) => {
      if (newWxid) {
        console.log('friendnick', FriendStore.friendnick);
        console.log('isconfirmpay', FriendStore.isconfirmpay);
      }
    },
    { immediate: true }
  );
</script>
